package huoye.shops.huoye.operation.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.codeideology.android.utils.StringUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseActivity;
import huoye.shops.huoye.operation.adapter.SharePondAdapter;
import huoye.shops.huoye.operation.model.EventInfo;
import huoye.shops.huoye.operation.model.EventOddPrizeList;
import huoye.shops.huoye.operation.model.GuessAll;
import huoye.shops.huoye.operation.model.ManageEventData;
import huoye.shops.huoye.operation.model.Prize;
import huoye.shops.huoye.operation.model.SharePondData;
import huoye.shops.huoye.operation.model.SharePool;
import huoye.shops.huoye.operation.model.ToUrl;
import huoye.shops.huoye.operation.presenter.SharePondPresenter;
import huoye.shops.huoye.operation.view.ISharePondView;
import huoye.shops.huoye.operation.widget.EventCodeDialog;
import huoye.shops.utils.StockUtils;
import huoye.shops.utils.ViewUtils;
import huoye.shops.widget.CommonHintDialog;
import huoye.shops.widget.RoundImageView;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_INTENT_PRIZE_TYPE_URL;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_KEY_PRIZE_SELECT_IMAGE;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_KEY_PRIZE_SELECT_PRIZE_ID;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_KEY_PRIZE_SELECT_STOCK;
import static huoye.shops.huoye.operation.activity.ManagePrizeActivity.EXTRAS_KEY_PRIZE_TYPE;
import static huoye.shops.utils.StockUtils.setTimeStyle;

public class SharePondActivity extends BaseActivity implements ISharePondView {

    @BindView(R.id.share_pond_tv_rule)
    TextView tvRule;
    @BindView(R.id.share_pond_tv_join_user)
    TextView tvJoinUser;
    @BindView(R.id.share_pond_tv_pond_limit)
    TextView tvPondLimit;
    @BindView(R.id.share_pond_tv_mine_put_limit)
    TextView tvMinePutLimit;

    @BindView(R.id.share_pond_tv_join_set)
    TextView tvJoinSet;

    @BindView(R.id.share_pond_tv_lottery_num)
    TextView tvLotteryNum;

    @BindView(R.id.share_pond_ll_lottery_num)
    LinearLayout llLotteryNum;

    @BindView(R.id.share_pond_ll_join_user)
    LinearLayout llJoinUser;

    @BindView(R.id.share_pond_ll_pond_limit)
    LinearLayout llPondLimit;

    @BindView(R.id.share_pond_ll_mine_put_limit)
    LinearLayout llMinePutLimit;

    @BindView(R.id.share_pond_ll_naming)
    LinearLayout llNaming;


    @BindView(R.id.item_qmccl_share_set_rv)
    RelativeLayout rvQmccl;
    @BindView(R.id.item_qmccl_share_set_tv_winning)
    TextView tvWinning;
    @BindView(R.id.item_qmccl_share_set_tv_prize_number)
    TextView tvPrizeNumber;
    @BindView(R.id.item_qmccl_share_set_iv_add_image)
    ImageView ivAddImage;
    private EventOddPrizeList eventOddPrizeQmccl = new EventOddPrizeList();;
    private EventInfo eventInfo;

    @OnClick(R.id.item_qmccl_share_set_iv_add_image)
    void onAddImageQmcclClick() {
        isQmccl = true;
        Intent intent = new Intent(getApplicationContext(), ManagePrizeActivity.class);
        intent.putExtra(EXTRAS_KEY_PRIZE_TYPE, "1");
        startActivityForResult(intent, EXTRAS_INTENT_PRIZE_TYPE_URL);
    }


    @BindView(R.id.share_pond_tv_naming_shop)
    TextView tvNamingShop;
    @BindView(R.id.share_pond_tv_naming_shop_hint)
    TextView tvNamingShopHint;
    @BindView(R.id.share_pond_rv_naming_head)
    RoundImageView rvNamingHea;

    @BindView(R.id.share_pond_tv_residue_time_day)
    TextView tvTimeOne;
    @BindView(R.id.share_pond_tv_residue_time_hout)
    TextView tvTimeTwo;
    @BindView(R.id.share_pond_tv_residue_time_minute)
    TextView tvTimeThree;
    @BindView(R.id.share_pond_btn_join_affirm)
    Button btnJoinAffirm;


    @BindView(R.id.share_pond_rv)
    RecyclerView rv;

    private boolean isQmccl = false;
    private int position;


    private List<EventOddPrizeList> eventOddPrizeList;

    private SharePondAdapter adapter;


    @Override                           //requestCode请求标记,resultCode是返回标记
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == EXTRAS_INTENT_PRIZE_TYPE_URL) {
            String number = data.getStringExtra(EXTRAS_KEY_PRIZE_SELECT_STOCK);
            String image = data.getStringExtra(EXTRAS_KEY_PRIZE_SELECT_IMAGE);
            String prizeId = data.getStringExtra(EXTRAS_KEY_PRIZE_SELECT_PRIZE_ID);

            if (isQmccl) {
               // tvPrizeNumber.setText(number);
                //目前写死  参加全民猜猜乐只用一个奖品
                tvPrizeNumber.setText("1/1");
                Glide.with(this)
                        .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + image)
                        .dontAnimate()
                        .placeholder(R.mipmap.ic_wait_logo)
                        .error(R.mipmap.ic_error)
                        .into(ivAddImage);
                eventOddPrizeQmccl.setPrizeNum(number);
                eventOddPrizeQmccl.setPrizeImg(image);
                eventOddPrizeQmccl.setPrizeId(prizeId);

            } else {
                eventOddPrizeList.get(position).setPrizeNum(number);
                eventOddPrizeList.get(position).setPrizeImg(image);
                eventOddPrizeList.get(position).setPrizeId(prizeId);
                eventOddPrizeList.get(position).setLocal(false);
                adapter.notifyDataSetChanged();
            }


        }
    }


    private SharePondPresenter mSharePondPresenter;


    @OnClick(R.id.share_pond_btn_join_affirm)
    void onJoinAffirmClick() {
        if (eventInfo.getCreateType() == 0) {
            if (eventInfo.getEtClassType() == 1) {
                addGxjcEvent();
            } else {
                addQmcclEvent();
            }
        } else {
            //自己的活动可以删除
            showDeleteHint();
        }
    }

    private void showDeleteHint() {
        CommonHintDialog commonHintDialog = new CommonHintDialog(this);
        commonHintDialog.setOnCommonHintListener(new CommonHintDialog.OnCommonHintListener() {
            @Override
            public void onLeftClick() {

            }

            @Override
            public void onRightClick() {
                //自己的活动可以删除
                mSharePondPresenter.cancelEvent(eventInfo.getEventId());
            }
        });
        commonHintDialog.show();
        commonHintDialog.setDialogContent("确定取消活动？", "取消", "确定");

    }


    private void addGxjcEvent() {
        for (int i = 0; i < eventOddPrizeList.size(); i++) {
            if (eventOddPrizeList.get(i).getPrizeNum().equals("0")) {
                makeToast("奖品数量不能为空");
                return;
            }
        }
        String temp = "";
        for (int i = 0; i < eventOddPrizeList.size() - 1; i++) {
            temp = eventOddPrizeList.get(i).getPrizeId();
            for (int j = i + 1; j < eventOddPrizeList.size(); j++) {
                if (temp.equals(eventOddPrizeList.get(j).getPrizeId())) {
                    makeToast("同个奖品不能分两次填入");
                    return;
                }
            }
        }



        mSharePondData.getSharePool().setEventOddPrizeList(eventOddPrizeList);
        mSharePondPresenter.joinEvent(mSharePondData);
    }

    private void addQmcclEvent() {
        List<EventOddPrizeList> listQmccl = new ArrayList<>();
        if(!StringUtils.isNotEmpty(eventOddPrizeQmccl.getPrizeId())){
            makeToast("参与活动的奖品不能为空");
            return;
        }
        if(!StringUtils.isNotEmpty(eventOddPrizeQmccl.getPrizeNum())||eventOddPrizeQmccl.getPrizeNum().equals("0")){
            makeToast("奖品数量不能为空");
            return;
        }

        listQmccl.add(eventOddPrizeQmccl);
        mSharePondData.getSharePool().setEventOddPrizeList(listQmccl);
        mSharePondPresenter.joinEvent(mSharePondData);

    }


    private Date eDate;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_share_pond;
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        setTitle("共享奖池");
        ManageEventData eventData = getIntentData();

        mSharePondPresenter = new SharePondPresenter();
        mSharePondPresenter.addTaskListener(this);
        mSharePondPresenter.onStart();
        mSharePondPresenter.getEventDetail(eventData.getEventId());


    }


    @Override
    public void onTopRightIvClick() {
        super.onTopRightIvClick();
        mSharePondPresenter.eventToUrl(mSharePondData.getEventInfo().getEventId());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(mRunnable);
    }

    private Handler handler = new Handler();
    private Runnable mRunnable;

    private void timer() {
        mRunnable = new Runnable() {
            @Override
            public void run() {
                if (eDate != null) {
                    showDistanceTime(eDate);
                }
                handler.postDelayed(this, 1000);
            }
        };
        handler.postDelayed(mRunnable, 1000);
    }


    private void showDistanceTime(Date endDate) {
        Date now = new Date();

        long hour = ViewUtils.getDistanceTimeHourDay(now, endDate);
        long min = ViewUtils.getDistanceTimemin(now, endDate);
        long second = ViewUtils.getDistanceTimeSecond(now, endDate);

        if (hour == 0 && min == 0 && second == 0) {
            makeToast("活动结束");
            hideRightBtn();
            btnJoinAffirm.setVisibility(GONE);
            handler.removeCallbacks(mRunnable);
            tvTimeOne.setText("00");
            tvTimeTwo.setText("00");
            tvTimeThree.setText("00");
            eDate = null;

        }

        if (hour == 0 && min == 0) {
            tvTimeOne.setText("00");
            tvTimeTwo.setText("00");
            tvTimeThree.setText(setTimeStyle(second));
        } else if (hour == 0) {
            tvTimeOne.setText("00");
            tvTimeTwo.setText(setTimeStyle(min));
            tvTimeThree.setText(setTimeStyle(second));
        } else {
            tvTimeOne.setText(setTimeStyle(hour));
            tvTimeTwo.setText(setTimeStyle(min));
            tvTimeThree.setText(setTimeStyle(second));
        }


    }


    private SharePondData mSharePondData;

    private String EventType = "1";

    @Override
    public void setEventData(SharePondData sharePondData) {
        this.mSharePondData = sharePondData;
        eventInfo = sharePondData.getEventInfo();


        if (eventInfo.getCreateType() == 1) {
            //自己的活动可以删除
            btnJoinAffirm.setText("取消活动");
            llLotteryNum.setVisibility(VISIBLE);
            llJoinUser.setVisibility(GONE);
            llPondLimit.setVisibility(GONE);
            llMinePutLimit.setVisibility(GONE);
            setTitle("自建活动");
            tvJoinUser.setText(eventInfo.getTotalNum());
            tvLotteryNum.setText(sharePondData.getSharePool().getUserLotteryNum());
            setRightTv("活动二维码");
            showRightBtn();
        } else {
            // 1.共享奖池  2.全民猜猜乐
            switch (eventInfo.getEtClassType()) {
                case 1:
                    showGXJC();
                    break;
                case 2:
                    showQMCCL();
                    break;
            }
        }

        String endTime = eventInfo.getEndTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            eDate = sdf.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //活动状态 0-未开始 1-已开始 2-已结束
        if (sharePondData.getEventInfo().getiState() == 2) {
            tvTimeOne.setText("00");
            tvTimeTwo.setText("00");
            tvTimeThree.setText("00");
            btnJoinAffirm.setVisibility(View.INVISIBLE);
            btnJoinAffirm.setEnabled(false);
            btnJoinAffirm.setClickable(false);
            hideRightBtn();
        } else {
            timer();
        }

        BigDecimal moeny = StockUtils.moenyStyle(eventInfo.getTotalMoney());
        tvPondLimit.setText(moeny + "");

        BigDecimal mineMoeny = StockUtils.moenyStyle(eventInfo.getCurrentTotalMoney());
        tvMinePutLimit.setText(mineMoeny + "");

        if (eventInfo.getRemarks() == null) {
            eventInfo.setRemarks("");
        }
        tvRule.setText(eventInfo.getRemarks());
        tvRule.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvRule.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //通知父控件不要干扰
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                }
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    //通知父控件不要干扰
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                }
                return false;
            }
        });


        showRvSharePond();

    }


    //显示共享奖池的数据
    private void showGXJC() {
        SharePool sharePool = mSharePondData.getSharePool();
        if (sharePool.isJoin()) {
            btnJoinAffirm.setVisibility(View.INVISIBLE);
            setRightTv("活动二维码");
            showRightBtn();
        } else {
            btnJoinAffirm.setVisibility(VISIBLE);
        }

    }


    private void showRvSharePond() {
        SharePool sharePool = mSharePondData.getSharePool();
        eventOddPrizeList = sharePool.getEventOddPrizeList();
        adapter = new SharePondAdapter(this, EventType);
        adapter.setData(eventOddPrizeList);
        adapter.setOnSharePondListener(new SharePondAdapter.OnSharePondListener() {
            @Override
            public void onAddPrizeClick(EventOddPrizeList eventOddPrizeList, int i) {
                //自建活动成功，还能更改奖品的图片，已经发布成功的活动，只能取消操作，其他都是不能更改了
                if (eventInfo.getCreateType() == 1 || sharePool.isJoin()) {


                } else {
                    Intent intent = new Intent(getApplicationContext(), ManagePrizeActivity.class);
                    intent.putExtra(EXTRAS_KEY_PRIZE_TYPE, "1");
                    startActivityForResult(intent, EXTRAS_INTENT_PRIZE_TYPE_URL);
                    position = i;
                }
            }


        });
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(adapter);
    }


    //显示全民猜猜乐的数据
    private void showQMCCL() {
        GuessAll guessAll = mSharePondData.getGuessAll();
        rv.setVisibility(GONE);
        llNaming.setVisibility(VISIBLE);
        setTitle(mSharePondData.getEventInfo().getEtClassName());
        EventType = "2";
        hideRightBtn();

        //是否当前商家冠名
        if (guessAll.isCurShopNaming()) {
            rvQmccl.setVisibility(VISIBLE);
            Prize prize = guessAll.getPrize();
            tvPrizeNumber.setText(prize.getPrizeNum());
            Glide.with(this)
                    .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + prize.getPrizeImg())
                    .dontAnimate()
                    .placeholder(R.mipmap.ic_wait_logo)
                    .error(R.mipmap.ic_error)
                    .into(ivAddImage);
        } else {
            rvQmccl.setVisibility(GONE);
        }


        if (guessAll.isJoin() || guessAll.isNaming()) {
            tvJoinSet.setVisibility(View.INVISIBLE);
            btnJoinAffirm.setVisibility(View.INVISIBLE);
            tvNamingShopHint.setText(guessAll.getShopName());
            Glide.with(this)
                    .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + guessAll.getShopLogo())
                    .dontAnimate()
                    .placeholder(R.mipmap.ic_wait_logo)
                    .error(R.mipmap.ic_error)
                    .into(rvNamingHea);
        } else {
            rvQmccl.setVisibility(VISIBLE);
            btnJoinAffirm.setVisibility(VISIBLE);
        }
    }


    @Override
    public void getEventUrl(ToUrl toUrl) {
        EventCodeDialog eventCodeDialog = new EventCodeDialog(this);
        eventCodeDialog.show();
        eventCodeDialog.encode(toUrl.getUrl());
    }


}
